from flask import request, Blueprint
from flask_restful import Api, Resource
from models.init_sqlalchemy import db
from models.models import Favorites, User, Posts
import uuid
from flask_jwt_extended import jwt_required, get_jwt_identity
from utils.h_result import HResult
from datetime import datetime
from utils.utils import to_beijing_time

bp = Blueprint('favorites', __name__, url_prefix='/favorites/')

class AddFavorite(Resource):
    method_decorators = [jwt_required()]
    
    def post(self):
        data = request.get_json()
        post_id = data.get('post_id')
        record_id = data.get('record_id')
        current_user = get_jwt_identity()
        
        if not (post_id or record_id):
            return HResult().get_result('error', '参数错误!')
            
        user = User.query.filter_by(name=current_user).first()
        
        # 检查帖子是否存在且未删除
        if post_id:
            post = Posts.query.filter_by(id=post_id, del_flag='1').first()
            if not post:
                return HResult().get_result('error', '帖子不存在!')

        # 检查是否已经收藏
        existing_favorite = Favorites.query.filter_by(
            user_id=user.id,
            post_id=post_id or '',
            record_id=record_id or ''
        ).first()
        
        if existing_favorite:
            return HResult().get_result('error', '已经收藏过了!')
            
        favorite = Favorites(
            id=str(uuid.uuid4()),
            user_id=user.id,
            post_id=post_id or '',
            record_id=record_id or '',
            created_time=to_beijing_time(datetime.utcnow())
        )
            
        db.session.add(favorite)
        db.session.commit()
        return HResult().get_result('success', '收藏成功!')

class CancelFavorite(Resource):
    method_decorators = [jwt_required()]
    
    def post(self):
        data = request.get_json()
        favorite_id = data.get('favorite_id')
        current_user = get_jwt_identity()
        
        if not favorite_id:
            return HResult().get_result('error', '参数错误!')
            
        user = User.query.filter_by(name=current_user).first()
        
        favorite = Favorites.query.filter_by(
            id=favorite_id,
            user_id=user.id
        ).first()
        
        if favorite:
            db.session.delete(favorite)
            db.session.commit()
            return HResult().get_result('success', '取消收藏成功!')
        else:
            return HResult().get_result('error', '收藏记录不存在!')

class QueryUserFavorites(Resource):
    method_decorators = [jwt_required()]
    
    def get(self):
        current_user = get_jwt_identity()
        user = User.query.filter_by(name=current_user).first()
        
        # 只查询未删除的帖子的收藏
        favorites = (Favorites.query
                    .join(Posts, Favorites.post_id == Posts.id)
                    .filter(Favorites.user_id == user.id)
                    .filter(Posts.del_flag == '1')
                    .all())
                    
        return HResult().get_result('success', data=[{
            'id': fav.id,
            'post': fav.post.to_dict() if fav.post_id else None,
            'record': fav.record.to_dict() if fav.record_id else None,
            'created_time': fav.created_time.strftime('%Y-%m-%d %H:%M:%S')
        } for fav in favorites])

class QueryPostFavorites(Resource):
    method_decorators = [jwt_required()]
    
    def get(self):
        post_id = request.args.get('post_id')
        if not post_id:
            return HResult().get_result('error', '参数错误!')
            
        favorites = Favorites.query.filter_by(post_id=post_id).all()
        return HResult().get_result('success', data=[{
            'id': fav.id,
            'user': fav.user.to_dict(),
            'created_time': fav.created_time.strftime('%Y-%m-%d %H:%M:%S')
        } for fav in favorites])

api = Api(bp)
api.add_resource(AddFavorite, '/add/', endpoint='add')
api.add_resource(CancelFavorite, '/cancel/', endpoint='cancel')
api.add_resource(QueryUserFavorites, '/user-favorites/', endpoint='user_favorites')
api.add_resource(QueryPostFavorites, '/post-favorites/', endpoint='post_favorites') 